import { asyncRoutes, constantRoutes } from '@/router'
import { getMenu } from '@/api/menu'
import Layout from '@/layout'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

export function generateMenu(routes, data) {
  // console.log(data)
  data.forEach(item => {
    const menu = {
      path: item.path,
      component: item.controllerName === null ? Layout : loadView('/user/index'),
      // hidden: item.visible !== '0',
      children: [],
      name: item.moduleName,
      meta: {
        title: item.moduleName,
        icon: item.icon,
        elicon: item.elicon,
        noCache: true
      }
    }
    // debugger
    if (item.childModuleList) {
      generateMenu(menu.children, item.childModuleList)
    }
    routes.push(menu)
  })
}

export const loadView = (view) => {
  return (resolve) => require(['@/views' + view], resolve)
}

const actions = {
  generateRoutes({ commit }, roles) {
    console.log('modules/permission')
    return new Promise(resolve => {
      const loadMenuData = []

      // debugger
      getMenu().then(response => {
        if (response.code !== 200) {
          this.$message({
            message: '菜单数据加载异常',
            type: 0
          })
        } else {
          const data = response.data
          Object.assign(loadMenuData, data)
          asyncRoutes.length = 0
          generateMenu(asyncRoutes, loadMenuData)
          asyncRoutes.push({

            // path: '/user/detail/:id(\\d+)',
            // component: () => import('@/views/user/detail'),
            // name: 'user',
            // meta: { title: '用户', noCache: true },
            // hidden: true

            path: '1000',
            component: Layout,
            redirect: '/user',
            children: [
              {
                path: '/user/detail/:id(\\d+)',
                component: () => import('@/views/user/detail'),
                name: 'user',
                meta: { title: '用户详情', noCache: true, activeMenu: '/user/index' },
                hidden: true
              }
            ]
          })
          asyncRoutes.push({ path: '*', redirect: '/404', hidden: true })

          console.log(asyncRoutes[6])
          console.log(asyncRoutes[7])
          commit('SET_ROUTES', asyncRoutes)
          resolve(asyncRoutes)
        }
      }).catch(error => {
        console.log(error)
      })
      // let accessedRoutes
      // if (roles.includes('admin')) {
      //   accessedRoutes = asyncRoutes || []
      // } else {
      //   accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      // }
      // commit('SET_ROUTES', accessedRoutes)
      // resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
